<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>JS 事件委托</title>
  <style>
    *{
      margin: 0;
      padding: 0;
    }
    ul{
      list-style: none;
      width: 400px;
      border: 1px solid #000;
      margin: 100px auto;
    }
    li{
      width: 100%;
      height: 50px;
      border-bottom: 1px solid #000;
      box-sizing: border-box;
    }
    .selected{
      background-color: red;
    }
  </style>
</head>
<body>
  <ul>
    <li class="selected">1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
    <li>7</li>
    <li>8</li>
  </ul>

  <!-- <script>
    // 未使用事件委托
    let uItems = document.querySelectorAll('li');
    let currentItem = uItems[0];
    for (let item of uItems){
      item.onclick = changeBg;
    }

    function changeBg() {
      currentItem.className = '';
      this.className = 'selected';
      currentItem = this;
    }
  </script> -->

  <script>
    // 利用事件冒泡, 监听ul的点击，而不是直接监听li的点击，li将事件冒泡到它的父元素ul，再通过事件对象拿到当前被点击的元素
    let oUl = document.querySelector('ul');
    let oLi = document.querySelector('.selected');
    oUl.onclick = function (event) {
      event = event || window.event; // 兼容所有浏览器
      oLi.className = '';
      let item = event.target; // event.target为当前点击的li
      item.className = 'selected';
      oLi = item;
    }
  </script>
</body>
</html>